package cn.tedu.tea.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 文件上传工具类
 */
@Slf4j
public class FileUtil {

    /**
     * 上传图片
     * @param file
     * @param path
     * @return
     * @throws Exception
     */
    public static String makeTempFile(MultipartFile file,String path) throws Exception {
//        log.debug("开始处理图片上传，参数{} | {}",file,path);
        File dir = new File(path);
        if (!dir.getParentFile().exists()){
            dir.getParentFile().mkdirs();
        }
        String fileName = System.currentTimeMillis() + "" + file.getOriginalFilename();
        File filePath = new File(path, fileName);
        if (!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
        }
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filePath));
        out.write(file.getBytes());
        out.flush();
        out.close();
        return fileName;
    }

    /**
     *
     * 获取文件名后缀
     * @param file
     * @return
     */
    public static String getFileExtension(MultipartFile file){
        String fileName = file.getOriginalFilename();
        if(fileName != null && fileName.length() > 0){
            int dotIndex = fileName.lastIndexOf('.');
            if (dotIndex > -1 && dotIndex < fileName.length() - 1){
                return fileName.substring(dotIndex + 1);
            }
        }
        return "";
    }
}
